package com.hjs.消费者生产者.方式一;


//使用wait和notify
public class ProducerConsumerWithWaitNofity {
    public static void main(String[] args) {
        Resource resource = new Resource();
        ProducerThread producerThread1 = new ProducerThread(resource);
        ProducerThread producerThread2 = new ProducerThread(resource);
        ProducerThread producerThread3 = new ProducerThread(resource);
        ConsumerThread consumerThread1 = new ConsumerThread(resource);
//        ConsumerThread consumerThread2 = new ConsumerThread(resource);
//        ConsumerThread consumerThread3 = new ConsumerThread(resource);
        producerThread1.start();
        producerThread2.start();
        producerThread3.start();
        consumerThread1.start();
//        consumerThread2.start();
//        consumerThread3.start();
    }

    static class Resource {
        private int num = 0;
        private int size = 10;

        public synchronized void remove() {
            if (num > 0) {
                num--;
                System.out.println("消费者" + Thread.currentThread().getName() + "消耗了一件资源，" + "当前线程还有" + num + "个");
                notifyAll();
            } else {
                try {
                    wait();
                    System.out.println("消费者" + Thread.currentThread().getName() + "线程进入等待状态");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public synchronized void add() {
            if (num < size) {
                num++;
                System.out.println(Thread.currentThread().getName() + "生产者生产了一件，现在有" + num + "件");
                notifyAll();
            } else {
                try {
                    wait();
                    System.out.println(Thread.currentThread().getName() + "进入了等待状态");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //消费者
    static class ConsumerThread extends Thread {
        private Resource resource;

        public ConsumerThread(Resource resource) {
            this.resource = resource;
        }
        @Override
        public void run(){
            while (true){
                try {
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.remove();
            }
        }
    }

    static class ProducerThread extends Thread{
        private Resource resource;
        public ProducerThread(Resource resource){
            this.resource = resource;
        }
        @Override
        public void run(){
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            resource.add();
        }
    }

}
